package org.example.forum.service.impl;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.example.forum.common.AppResult;
import org.example.forum.common.ResultCode;
import org.example.forum.common.StringUtils;
import org.example.forum.dao.ArticleMapper;
import org.example.forum.dao.ArticleReplyMapper;
import org.example.forum.exception.ApplicationException;
import org.example.forum.model.Article;
import org.example.forum.model.ArticleReply;
import org.example.forum.service.IArticleReplyService;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleReplyServiceImpl implements IArticleReplyService {
    @Resource
    private ArticleReplyMapper articleReplyMapper;
    @Resource
    private ArticleMapper articleMapper;
    @Override
    @Transactional
    public void create(ArticleReply articleReply) {
    if(articleReply==null|| StringUtils.isEmpty(articleReply.getContent())
                          ||articleReply.getArticleId()==null
                            || articleReply.getReplyUserId()==null){
        log.info("某个参数不合法");
        throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
    }
        articleReply.setReplyId(null);
        articleReply.setReplyUserId(null);
        articleReply.setLikeCount(0);
        articleReply.setState((byte) 0);
        articleReply.setDeleteState((byte) 0);
        Date date = new Date();
        articleReply.setCreateTime(date);
        articleReply.setUpdateTime(date);
        int row=articleReplyMapper.insertSelective(articleReply);
        if(row==0){
            log.info("数据库添加失败{}",articleReply.getContent());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        Article article = articleMapper.selectByPrimaryKey(articleReply.getArticleId());
        article.setReplyCount(article.getReplyCount()+1);
         Date data=new Date();
         article.setUpdateTime(data);
         article.setId(articleReply.getArticleId());
         row=articleMapper.updateByPrimaryKeySelective(article);
         if(row==0){
             throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
         }
        log.info("添加成功帖子{}",articleReply.getContent());
    }

    @Override
    public List<ArticleReply> selectByArticleId(Long articleId) {
         if(articleId==null||articleId<=0){
             throw new ApplicationException(AppResult.failed((ResultCode.FAILED_PARAMS_VALIDATE)));
         }
         List<ArticleReply> list=articleReplyMapper.selectByArticleId(articleId);
         return list;

    }
}
